package fhv.at.imageprocessing.laplaceImage;

import java.io.Serializable;

import javax.media.jai.KernelJAI;
import javax.media.jai.PlanarImage;

import fhv.at.imageprocessing.ImageChangedEvent;
import fhv.at.imageprocessing.ImageChangedListener;
import fhv.at.imageprocessing.ImageHelper;
import fhv.at.imageprocessing.ImageNeededEvent;
import fhv.at.imageprocessing.ImageProcessor;

/**
 * Laplace image bean
 * 
 * @author phru
 * 
 */
public class LaplaceImage implements ImageChangedListener, Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private KernelJAI kernel;
	private final ImageHelper imageHelper;
	private PlanarImage planarImage;

	public LaplaceImage() {
		int maxParents = 1;
		imageHelper = new ImageHelper(maxParents, this);
		float[] kernelData = { 0.0F, -1.0F, 0.0F, -1.0F, 4.0F, -1.0F, 0.0F,
				-1.0F, 0.0F, };
		kernel = new KernelJAI(3, 3, kernelData);
	}

	public KernelJAI getKernel() {
		return kernel;
	}

	public void setKernel(KernelJAI kernel) {
		this.kernel = kernel;
		imageHelper.fireImageNeededEvent();
	}

	/* Eigentliche Bildbearbeitung */
	@Override
	public void manipulateImage() {
		if (planarImage != null) {
			ImageProcessor ip = ImageProcessor.getInstance();
			planarImage = ip.getLaplace(planarImage, kernel);
			imageHelper.fireImageChangedEvent();
		}
	}

	/* Implementation fur Eventregistrierung */
	@Override
	public void addImageChangedListener(ImageChangedListener icl) {
		imageHelper.addImageChangedListener(icl);
	}

	@Override
	public void removeImageChangedListener(ImageChangedListener icl) {
		imageHelper.removeImageChangedListener(icl);
	}

	@Override
	public void addImageNeededListener(ImageChangedListener icl) {
		imageHelper.addImageNeededListener(icl);
	}

	@Override
	public void removeImageNeededListener(ImageChangedListener icl) {
		imageHelper.removeImageNeededListener(icl);
	}

	/* Implementation fur ImageChangedListener */
	@Override
	public void imageValueChanged(ImageChangedEvent ice) {
		System.out.println(getClass().getSimpleName() + " imageValueChanged");
		planarImage = imageHelper.getPlanarImage(ice);
		manipulateImage();
	}

	@Override
	public void imageNeeded(ImageNeededEvent ice) {
		System.out.println(getClass().getSimpleName() + " imageNeeded");
		imageHelper.fireImageChangedEvent();
		// imageHelper.fireImageChangedEvent(ice);
	}

	@Override
	public ImageChangedListener getRefFromSource() {
		return this;
	}

	@Override
	public PlanarImage getPlanarImage() {
		return planarImage;
	}

}
